<?php

class Util_File {

	static private function _base(){
		//$instance = (Utils::getSetup('zend_instance_owner_id')=='1'?'ccp':'cp');
		return APPLICATION_PATH.'/../public/upload/';//.$instance;
	}
	
	static public function handleUpload($fieldName){
		$rq = Zend_Controller_Front::getInstance()->getRequest();
		
		if(empty($_FILES)&& empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && 
			strtolower($_SERVER['REQUEST_METHOD']) == 'post'){
				$mps = str_replace('M','',ini_get('post_max_size'));
				Validation::react("Za duży plik. (max 5 MB) [post $mps MB]");
		} else {
			$file =  $_FILES[$fieldName];
			if ($file['error'] == UPLOAD_ERR_OK) {
				if ($file['size'] < 1 || $file['size'] > 5000000){
					Validation::react("Za duży rozmiar pliku: ".substr($file['size']/1000000,0,4)." MB.");
				}
				$rq->setParam($fieldName,str_replace(' ', '_', $file['name']));
			} else if ($file['error'] == 1){
				$mps = ini_get('upload_max_filesize');
				Validation::react("Za duży plik. (max 5 MB) [upload $mps]");
			} else {
				$file = false;
			}
		}
		return $file;
	}
	
	static public function finishHim($file,$object,$id){
		$_ = self::_base();
		if (!$file || move_uploaded_file($file['tmp_name'],$_.$object.'_'.$id)){
			return true;
		} else Validation::react("d".$file);// TODO co to i po co to tu?
	}
	
	static public function delete($what,$id){
		$path = self::_base().'_'.$what.'_'.$id;
		//Utils::log($path);
		return 
			file_exists($path) ? unlink($path) : false;
		;
	}
	
	static public function download($what,$id,$name){
		
		$path = self::_base().'_'.$what.'_'.$id;
		 
		if ($fd = fopen ($path, "r")){
		    $fsize = filesize($path);
		    $path_parts = pathinfo($path);// TODO co to?
			header("Content-type: application/octet-stream");
			header("Content-Disposition: filename=\"".$name."\"");
		    header("Content-length: $fsize");
		    header("Cache-control: private");
		    while(!feof($fd)) {
		        $buffer = fread($fd, 2048);
		        echo $buffer;
		    }
		}
		fclose ($fd);
	}
	
}